#include "mainwindow.h"
#include "config.h"

#include <QDir>
#include <QDebug>
#include <QPainter>
#include <QTextBlock>



static uint8_t textSaveFlag = 0;


MainWindow::MainWindow(int idx, const QJsonObject &data, QWidget *parent)
    : QMainWindow{parent}
{

    messageBox = new QMessageBox;
    messageBox->addButton(QMessageBox::Cancel);
    messageBox->addButton(QMessageBox::Ok);
    messageBox->setDefaultButton(QMessageBox::Cancel);

    index = idx;
    confJsonObj = data;
    titleBar = new TitleBar;
    //titleBar->setTitle("老贴");
    textEdit = new TextEdit;

    statusBar = new QStatusBar;
    this->setStatusBar(statusBar);
    this->statusBar->hide();
#if 0
    QImage back(":/pics/editor-back.png");
    QRect re(QPoint(textEdit->geometry().x(), textEdit->geometry().y()), textEdit->size());
    QPainter *p = new QPainter(textEdit);
    p->drawImage(re, back);
#endif

    mainLyt = new QGridLayout;
    mainLyt->setMargin(0);
    mainLyt->setSpacing(0);
    mainLyt->addWidget(titleBar, 0, 0, 1, 2);

    mainLyt->addWidget(textEdit, 1, 0, 1, 2);
    mainWidget = new QWidget;
    mainWidget->setLayout(mainLyt);
    this->setCentralWidget(mainWidget);

#if 1
    foldAction = new QAction;
    foldAction->setIcon(QIcon(":/icons/fold.png"));
    foldAction->setToolTip(tr("收起"));
    linenumberAction = new QAction;
    linenumberAction->setIcon(QIcon(":/icons/number.png"));
    linenumberAction->setToolTip(tr("显示/关闭行号"));
    ontopAction = new QAction;
    ontopAction->setIcon(QIcon(":/icons/ontop.png"));
    ontopAction->setToolTip(tr("打开/关闭置顶"));
    delAction = new QAction;
    delAction->setIcon(QIcon(":/icons/delete.png"));
    delAction->setToolTip(tr("永久删除"));

    toolBar = new QToolBar;

    toolBar->addAction(foldAction);
    toolBar->addAction(linenumberAction);
    //toolBar->addAction(ontopAction);
    toolBar->addAction(delAction);

    this->addToolBar(Qt::RightToolBarArea, toolBar);
    toolBar->hide();

#endif

    qssFile = new QFile(":/qss/mainwindow.qss");
    if (qssFile->open(QFile::ReadOnly)) {
        qssData = QString::fromUtf8(qssFile->readAll());
        this->setStyleSheet(qssData);
    }

    this->setWindowFlags(Qt::FramelessWindowHint | windowFlags());
    updateWindowFromConf();

    connect(titleBar, &TitleBar::closeWindow, this, &MainWindow::on_titleBar_closeWindow);
    connect(titleBar, &TitleBar::expand, this, &MainWindow::on_titleBar_expand);
    connect(titleBar, &TitleBar::moved, this, &MainWindow::on_titleBar_moved);
    connect(titleBar, &TitleBar::add, this, &MainWindow::on_titleBar_add);
    connect(titleBar, &TitleBar::pressed, this, &MainWindow::on_titleBar_pressed);
    connect(titleBar, &TitleBar::released, this, &MainWindow::on_titleBar_released);
    connect(foldAction, &QAction::triggered, this, &MainWindow::on_foldAction_triggered);
    connect(linenumberAction, &QAction::triggered, this, &MainWindow::on_linenumberAction_triggered);
    connect(ontopAction, &QAction::triggered, this, &MainWindow::on_ontopAction_triggered);
    connect(delAction, &QAction::triggered, this, &MainWindow::on_delAction_triggered);
    connect(messageBox, &QMessageBox::buttonClicked, this, &MainWindow::on_messageBox_buttonClicked);
    connect(textEdit, &QPlainTextEdit::textChanged, this, &MainWindow::on_textEdit_textChanged);

    loadText();

    startTimer(500);

}

QJsonObject MainWindow::jsonConf()
{
    return confJsonObj;
}

int MainWindow::indexOfList()
{
    return index;
}

void MainWindow::setIndexOfList(int idx)
{
    index = idx;
}

void MainWindow::wShow()
{
    this->show();
    this->move(confJsonObj["Xpos"].toInt(), confJsonObj["Ypos"].toInt());
}

void MainWindow::updateWindowFromConf()
{

    if (confJsonObj["StayOnTop"].toBool()) {
        this->setWindowFlag(Qt::X11BypassWindowManagerHint, true);
    } else {
        this->setWindowFlag(Qt::X11BypassWindowManagerHint, false);
    }
    if (confJsonObj["ShowToolBar"].toBool()) {
        toolBar->show();
    } else {
        toolBar->hide();
    }
    if (confJsonObj["ShowLineNumber"].toBool()) {
        textEdit->lineNumberCtrl(TextEdit::LineNumberEnable);
    } else {
        textEdit->lineNumberCtrl(TextEdit::LineNumberDisable);
    }
    if (!confJsonObj["Hidden"].toBool()) {
        wShow();
    }
}

void MainWindow::loadText()
{
    dataFile = new QFile(DATA_FILE_PATH(confJsonObj["File"].toString()));
    if (!dataFile->exists()) {
        dataFile->open(QFile::NewOnly);
        dataFile->close();
        return;
    }
    dataFile->open(QFile::ReadOnly | QFile::Text);
    textEdit->setPlainText(dataFile->readAll());
    dataFile->close();
}

void MainWindow::on_titleBar_closeWindow()
{
    dataFile->close();
    this->hide();
}

void MainWindow::on_titleBar_expand()
{
    toolBar->show();
    confJsonObj["ShowToolBar"] = true;
}

void MainWindow::on_titleBar_add()
{
    emit newWindow();
}

void MainWindow::on_titleBar_moved(const QPoint &pos)
{
    this->move(pos);
    confJsonObj["Xpos"] = pos.x();
    confJsonObj["Ypos"] = pos.y();
    this->statusBar->showMessage("x: " + QString::number(pos.x()) + " y: " + QString::number(pos.y()));
}

void MainWindow::on_titleBar_pressed()
{
    this->statusBar->show();
}

void MainWindow::on_titleBar_released()
{
    this->statusBar->hide();
}

void MainWindow::on_foldAction_triggered()
{
    toolBar->hide();
    confJsonObj["ShowToolBar"] = false;
}

void MainWindow::on_linenumberAction_triggered()
{
    if (confJsonObj["ShowLineNumber"].toBool()) {
        confJsonObj["ShowLineNumber"] = false;
        textEdit->lineNumberCtrl(TextEdit::LineNumberDisable);
    } else {
        confJsonObj["ShowLineNumber"] = true;
        textEdit->lineNumberCtrl(TextEdit::LineNumberEnable);
    }
}

void MainWindow::on_ontopAction_triggered()
{
    if (confJsonObj["StayOnTop"].toBool()) {
        confJsonObj["StayOnTop"] = false;
        this->setWindowFlag(Qt::X11BypassWindowManagerHint, false);
    } else {
        confJsonObj["StayOnTop"] = true;
        this->setWindowFlag(Qt::X11BypassWindowManagerHint, true);
    }
    this->show();
}

void MainWindow::on_delAction_triggered()
{
    messageBox->setWindowTitle(tr("警告"));
    messageBox->setText(tr(" 这将删除此便签的所有内容，继续删除？"));
    messageBox->show();
    messageBox->move(this->x() + this->width(), this->y() + 100);
}

void MainWindow::on_messageBox_buttonClicked(QAbstractButton *button)
{
    if (button->text() == "&OK") {
        dataFile->remove();
        emit closeWindow();
    }
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    event->accept();
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    this->hide();
    event->ignore();
}

void MainWindow::on_textEdit_textChanged()
{
    textSaveFlag = 1;
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    if (textSaveFlag) {
        textSaveFlag = 0;
        dataFile->open(QFile::WriteOnly);
        dataFile->write(textEdit->toPlainText().toUtf8());
        dataFile->close();
    }
    this->setWindowTitle(textEdit->document()->findBlockByLineNumber(0).text());
    event->accept();
}
